/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package XMLManager;

import Database.XMLManager.XMLUsersFile;
import exceptions.DatabaseException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Marcello Maggioni
 */
public class XMLUsers {

    private XMLUsersFile xuf;
    
    public XMLUsers() {
        try {
            xuf = (XMLUsersFile) XMLUsersFile.getDefaultInstance("D:\\tests");
        } catch (DatabaseException ex) {
            ex.printStackTrace();
        }
    }

    // TODO add test methods here.
    // The methods must be annotated with annotation @Test. For example:
    //
    // @Test
    // public void hello() {}
    
    /**
     * Try heavy multithreading user creation and manipulation
     */
    @Test
    public void createConcurrentUsers() {
        try {
            Thread t1 = new Thread(new CreateThread(xuf, 0));
            Thread t2 = new Thread(new CreateThread(xuf, 100));
            t1.start();
            t2.start();
            t1.join();
            t2.join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    
    @Test
    public void userManipulation() {
        try {
            xuf.changePassword("user199", "PWD2");
            assertTrue(xuf.verifyUser("user199", "PWD2"));
            assertFalse(xuf.verifyUser("user199", "PWD"));
            assertFalse(xuf.isAdmin("user199"));
            xuf.setAdmin("user199", true);
            assertTrue(xuf.isAdmin("user199"));
            xuf.setAdmin("user199", false);
            assertFalse(xuf.isAdmin("user199"));
            xuf.deleteUser("user199");
            assertFalse(xuf.verifyUser("user199", "PWD2"));
        } catch (DatabaseException ex) {
            return;
        }
        
        //fail();
    }

    class CreateThread implements Runnable {
        private XMLUsersFile xuf;
        private int initial;
        public CreateThread(XMLUsersFile xuf, int initial) {
            this.xuf = xuf;
            this.initial = initial;
        }
        
        public void run() {
            try {
                for (int i = initial; i < initial + 100; i++)
                    xuf.addUser("user" + i, "PWD", "User");
                for (int i = initial; i < initial + 100; i++)
                    assertFalse(xuf.verifyUser("user" + i, "PWD"));
                for (int i = initial; i < initial + 100; i++)
                    xuf.enableUser("user"+i);
                for (int i = initial; i < initial + 100; i++)
                    assertTrue(xuf.verifyUser("user" + i, "PWD"));
            } catch (DatabaseException ex) {
                ex.printStackTrace();
            }
            
        }
        
    }
}